<?php
/**
 * Created by PhpStorm.
 * User: TX
 * Date: 2020/2/14
 * Time: 10.19
 */

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\model\ApplyModel;

class Apply extends AdminController
{


    protected $ApplyModel;

    /**
     * 初始化
     * node constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->ApplyModel=new ApplyModel();//应用模型
    }

    /**
     * 应用列表
     */
    public function index()
    {
        // ajax访问
        if ($this->request->get('type') == 'ajax') {
            // 接收参数
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $select = (array)$this->request->get('select', []);

            $where = [['is_deleted', '=', 0]]; // 未被删除
            // 搜索条件
            foreach ($select as $k => $v)
            {
                if ($k == 'name' && $v != '') {
                    $where[] = ['name|short|manager_link', 'LIKE', '%' . $v . '%'];
                }
                if ($k == 'status' && $v != '') {
                    $where[] = ['status', '=', $v];
                }
            }
            // 列表查询
            $data = $this->ApplyModel->getAll($where, '*', $page, $limit,[], 'id desc');
            // 数量查询
            $count = $this->ApplyModel->getCount($where);
            // 数据组装
            $info = [
                'limit'        => $limit,
                'page_current' => $page,
                'page_sum'     => ceil($count / $limit),
            ];
            $msg = '暂无数据！';
            if ($data) {
                $msg = '查询成功！';
                foreach ($data as $k => &$v)
                {
                    //$v['status'] = $v['status']?config('admin.apply_status')[$v['status']]:'';
                    $v['create_time'] = $v['create_time']?dateTime($v['create_time']):'--';
                    $v['update_time'] = $v['update_time']?dateTime($v['update_time']):'--';
                }
            }
            $list = [
                'code'  => 0,
                'msg'   => $msg,
                'count' => $count,
                'info'  => $info,
                'data'  => $data,
            ];
            return json($list);
        }

        $status=config('admin.apply_status');
        // 基础数据
        $basic_data = [
            'title' => '应用列表',
            'data'  => '',
            'status'=>$status
        ];

        return $this->fetch('', $basic_data);
    }


    // 应用添加操作
    public function add()
    {
        //渲染添加页面
        if (!$this->request->isPost()) {
            //基础数据
            $basic_data = [
                'data' => '',
            ];
            $this->assign($basic_data);
            return $this->fetch();
        }else{
            //处理添加应用操作
            $post=$this->request->post();//接收参数

            if(empty($post['short'])){
                returnJson(0,'应用简称不能为空！');
            }
            $id=$this->ApplyModel->getOne(['short'=>$post['short'],'is_deleted'=>0],'id');

            if(!empty($id)){
                returnJson(0,'应用简称已经存在！');
            }

            $data=[
                'name'=>$post['name']??'',
                'short'=>$post['short']??'',
                'status'=>$post['status']??2,
                'manager_link'=>$post['manager_link']??'',
                'desc'=>$post['desc']??'',
                'weapp_qrcode'=>$post['speci']?json_encode($post['speci']):'',
                'create_time'=>time(),
            ];

            $res=$this->ApplyModel->add($data);

            if($res){
                return json(['code' => 1, 'msg' => '添加成功']);
            }
            return json(['code' => 0, 'msg' => '添加失败']);

        }



    }


    // 应用编辑操作
    public function edit()
    {
        // 渲染编辑页面
        if (!$this->request->isPost()) {
            // 接收参数
            $id = $this->request->get('id');

            // 获取应用信息
            $data = $this->ApplyModel->getOne(['id'=>$id]);
            if (empty($data)) return msg_error('暂无数据，请重新刷新页面！');

            $weapp_qrcode=$data['weapp_qrcode']?json_decode($data['weapp_qrcode'],true):'';
            foreach($weapp_qrcode as $k=>$v){
                $weapp_qrcode[$k]['norms_pic']=$v['norms_pic']?config('api.qi_niu_url').$v['norms_pic']:'';
            }
            $data['weapp_qrcode']=$weapp_qrcode;

            // 基础数据
            $basic_data = [
                'data'  => $data,
            ];
            $this->assign($basic_data);
            return $this->fetch('add');
        }
        // 处理编辑操作
        else {
            // 接收参数
            $post = $this->request->post();
            //清空菜单缓存
            clear_menu();

            if(empty($post['short'])){
                returnJson(0,'应用简称不能为空！');
            }
            $id=$this->ApplyModel->getOne(['short'=>$post['short'],'is_deleted'=>0],'id');
            if(!empty($id['id']) && $id['id']!=$post['id']){returnJson(0,'已有相同的应用简称！');}//验证编辑的时候应用简称*/

            if(!empty($post['speci'])){
                $speci=$post['speci'];
                foreach($speci as $k=>$v){
                    $speci[$k]['norms_pic']=str_replace(config('api.qi_niu_url'),'',$v['norms_pic']);
                }
            }
            $data=[
                'name'=>$post['name']??'',
                'short'=>$post['short']??'',
                'status'=>$post['status']??2,
                'manager_link'=>$post['manager_link']??'',
                'desc'=>$post['desc']??'',
                'weapp_qrcode'=>$post['speci']?json_encode($speci):'',
                'update_time'=>time(),
            ];

            $res=$this->ApplyModel->edit(['id'=>$post['id']],$data);


            if ($res) {
                return json(['code' => 1, 'msg' => '编辑成功']);
            }
            return json(['code' => 0, 'msg' => '编辑失败']);
        }
    }


    // 应用删除（逻辑删除）
    public function del()
    {
        // 接收参数
        $get = $this->request->get();

        // 验证数据
        if(empty($get['id'])){
            returnJson(0,'缺少参数');
        }

        $del = 0;
        // 批量删除操作
        if (is_array($get['id'])) {
            foreach ($get['id'] as $k => $v)
            {
                $where['id'] = $v;
                $data['is_deleted'] = 1;
                $del = $this->ApplyModel->edit($where, $data);
                unset($where);
            }
        }
        // 单条删除
        else {
            $where['id'] = $get['id'];
            $data['is_deleted'] = 1;
            $del = $this->ApplyModel->edit($where, $data);
            unset($where);
        }

        if ($del >= 1) {
            //清空菜单缓存
            clear_menu();
            return json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '数据有误，请刷新重试！']);
        }

    }

































}